package mcpplus

import (
	"gitee.com/hongzhaomin/gspring/iface"
	"gitee.com/hongzhaomin/gspringboot"
	"github.com/mark3labs/mcp-go/server"
	"reflect"
)

func Run(setMcpServers ...func(*server.MCPServer)) {
	var setMcpServer func(*server.MCPServer)
	if len(setMcpServers) > 0 {
		setMcpServer = setMcpServers[0]
	}

	// 添加mcp服务监听器和销毁处理器
	mcpServerListener := NewMcpServerListener(setMcpServer)
	gspringboot.NewGspringApplication().
		AddRunListeners(mcpServerListener).
		AddShutdownHandler(func() {
			mcpServerListener.Shutdown()
		}).Run()
}

func NewMcpServerListener(setMcpServer func(*server.MCPServer)) *McpServerListener {
	return &McpServerListener{
		setMcpServer: setMcpServer,
	}
}

var _ gspringboot.ApplicationRunListener = (*McpServerListener)(nil)

type McpServerListener struct {
	mcpServerManager *McpServerManager
	setMcpServer     func(*server.MCPServer)
}

func (my *McpServerListener) Ready(appCtx iface.ApplicationContext, _ gspringboot.ConfigurationEnvironment, logger iface.GspringLogger) {
	my.mcpServerManager = appCtx.GetBeanByRt(reflect.TypeOf((*McpServerManager)(nil))).(*McpServerManager)

	if my.setMcpServer != nil {
		// 允许自定义设置mcp server
		// 例如额外添加tool
		my.setMcpServer(my.mcpServerManager.mcpServer)
	}

	// 启动mcp server
	my.mcpServerManager.Start()
	logger.Info("mcp server ready")
}

func (my *McpServerListener) Shutdown() {
	if my.mcpServerManager != nil {
		my.mcpServerManager.Shutdown()
	}
}

func (my *McpServerListener) Starting(_ gspringboot.ConfigurationEnvironment, _ iface.GspringLogger) {

}

func (my *McpServerListener) ContextPrepared(_ iface.ApplicationContext, _ gspringboot.ConfigurationEnvironment, _ iface.GspringLogger) {

}

func (my *McpServerListener) Stared(_ iface.ApplicationContext, _ gspringboot.ConfigurationEnvironment, _ iface.GspringLogger) {

}
